const mongoose = require("mongoose")
//创建模型
const deSchema = new mongoose.Schema({
  username: { type: String },
  password: { type: String },
  key: { type: String },
})
//获取表中的数据
const data = mongoose.model("de", deSchema, "des")

module.exports = {
  //初始化，主要是链接MongoDB
  init() {
    mongoose.connect("mongodb://127.0.0.1:27017/de").then(() => {
      console.log("数据库链接成功")
    }).catch((err) => {
      console.warn(err)
    })
  },
  //对传递过来的用户名和密码进行校验
  async checkUser(username, password) {
    const user = await data.findOne({ username })
    return user && user.password === password
  },
  //添加用户
  async registerUser(username, password) {
    const user = await data.findOne({ username })
    if (user) {
      return false
    } else {
      data.insertMany([{
        username,
        password,
        key:"1"
      }])
      return true
    }
  },
  //查询所有数据
  async getList(){
   let res = await  data.find()
   return res
  },
  //删除
  async delItem(id){
    let res = await data.findByIdAndDelete(id)
    return res
  },
  //查询某一项数据
  async findItem(_id){
    let res = await data.findOne({_id})
    console.log(res)
    return res
  },
  //修改数据
  async edit(_id,obj){
    let res = await data.findByIdAndUpdate(_id,obj)
    return res
  }
}